<template>
	<view class="main flex flex-dir-c">
		<view>
			<u-search class="search" placeholder="搜索群/好友" v-model="allState.searchValue"
				:show-action="false"></u-search>
		</view>
		<view class="list f1">
			<scroll-view scroll-y class="scroll">
				<view v-for="item in allState.list" :key="item.userid">
					<view class="flex flex-ai-c list-item">
						<checkbox-group @change="checkSelectItem(item.userid)">
							<label>
								<checkbox :value="item.userid+''" :checked="item.checked" />
							</label>
						</checkbox-group>
						<image :src="item.handimg"></image>
						<view class="f1 list-item-info flex flex-dir-c flex-jc-c">
							<view style="margin-bottom: 20rpx;">{{item.nickname || item.username}}</view>
							<view>{{item.id?'在线':'离线'}}</view>
						</view>
						<view class="list-time">10:10</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view>
			<u-button @click="createCrowd">立即创建</u-button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import user from '@/api/user.js'
	import chat from '@/api/chat.js'
	let allState = reactive({
		searchValue: '',
		list: [],
		userinfo: uni.getStorageSync('userinfo')
	})
	const checkSelectItem = (e: string|number) => {
		let obj = allState.list.find(user => user.userid == e)
		if (obj.checked) {
			obj.checked = false
		} else {
			obj.checked = true
		}
	}
	//创建群
	const crowdCreate = async (list) => {
		const res = await chat.crowdCreate({
			title: '未命名群',
			img: '',
			announcement: ''
		})
		crowdAdd(list, res.data)
	}
	//邀请成员
	const crowdAdd = async (list: AnyArray,id: Number) => {
		const res = await chat.crowdAdd({
			list: list,
			crowd_id: id
		})
		uni.navigateBack()
	}
	
	const createCrowd = () => {
		let list = allState.list.filter(user => user.checked)
		list = [...list,allState.userinfo]
		if(!list.length) return
		crowdCreate(list)
	}
	//获取所有用户列表
	const followList = async () => {
		const res = await user.getUserList({
			username: ''
		})
		res.data.map((v: AnyObject) => {
			v.checked = false
		})
		allState.list = res.data
	}
	onLoad(() => {
		followList()
	})
</script>

<style lang="scss" scoped>
	@import '../../pages/news/index.scss';

	page {
		height: 100%;
	}

	.main {
		height: 100%;
	}

	.scroll {
		height: 100%;
	}
</style>